package com.card.manager.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.card.framework.page.model.PageModel;
import com.card.framework.security.MySecurityMetadataSource;
import com.card.framework.util.CommonUtil;
import com.card.framework.util.TreeBulid;
import com.card.manager.domain.Resources;
import com.card.manager.domain.Roles;
import com.card.manager.services.RoleService;

@Controller
@RequestMapping("/role")
public class RoleController {
	@Autowired(required=true) 
	private TreeBulid treeBulid;
	@Autowired(required=true) 
	private RoleService roleServices;
	@InitBinder
	public void setupDataBinder(WebDataBinder dataBinder) {
		//表单页面如果有时间类型的需要initbinder
		dataBinder.registerCustomEditor(String.class,new StringTrimmerEditor(false));  
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
//	@RequestMapping(value="/index")
//	public ModelAndView index(HttpServletRequest request,HttpSession session,
//			HttpServletResponse response){
//		Map<String,Object> temp = roleServices.loadAllInfo();
//		ModelAndView tempView = new ModelAndView();
//		tempView.addObject("users", temp.get("users"));
//		tempView.addObject("roles", temp.get("roles"));
//		tempView.addObject("resources", temp.get("resources"));
//		tempView.setViewName("roleList");
//		return tempView;
//	}
	@RequestMapping(value="/index")
	public String index(HttpServletRequest request,HttpSession session,
			HttpServletResponse response){
		return "roleList";
	}
	@RequestMapping(value="/queryList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> queryList(HttpServletRequest request,Roles role,PageModel pageModel) throws Exception{
		return roleServices.selectRoleForPage(role, pageModel);
	}
	@RequestMapping("/roleUpdateWindow")
	public String roleUpdateWindow(HttpServletRequest request,HttpSession session,
			HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		Roles role = null;
		if(StringUtils.isNotEmpty(id)){
			role = roleServices.getById(Integer.parseInt(id));
		}else{
			role = new Roles();
			role.setEnable(true);
			SecurityContext sc = (SecurityContext)request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
			role.setCreatuserid(sc.getAuthentication().getName());
		}
		request.setAttribute("role",role);
		return "/rolePopWindow";
	}
	@RequestMapping("/roleAddWindow")
	public String roleAddWindow(HttpServletRequest request,HttpSession session,
			HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		Roles role = null;
		if(StringUtils.isNotEmpty(id)){
			role = roleServices.getById(Integer.parseInt(id));
		}else{
			role = new Roles();
			role.setEnable(true);
			SecurityContext sc = (SecurityContext)request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
			role.setCreatuserid(sc.getAuthentication().getName());
		}
		request.setAttribute("role",role);
		return "/rolePopWindow";
	}
	/**
	 * 提交新增或修改,根据id是否为空判断.
	 * 返回提交成功后的数据.json格式
	 */
	@RequestMapping(value="/roleUpdate",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> roleUpdate(HttpServletRequest request,Roles role) throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		try { 
			if(role.getRoleid() == null){
				if(!roleServices.isExistName(role.getName())){
					roleServices.add(role);
					map.put("result", "succ");
				}else{
					map.put("result", "fail");
					map.put("reason", "exists");
				}
			}else{
				roleServices.update(role);
				map.put("result", "succ");
			}
		}
		catch (Throwable e) {
			CommonUtil.throwsException(map, e);
		}
		return map; 
	}
	/**
	 * 提交新增或修改,根据id是否为空判断.
	 * 返回提交成功后的数据.json格式
	 */
	@RequestMapping(value="/roleAdd",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> roleAdd(HttpServletRequest request,Roles role) throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		try { 
			if(role.getRoleid() == null){
				if(!roleServices.isExistName(role.getName())){
					roleServices.add(role);
					map.put("result", "succ");
				}else{
					map.put("result", "fail");
					map.put("reason", "exists");
				}
			}else{
				roleServices.update(role);
				map.put("result", "succ");
			}
		}
		catch (Throwable e) {
			CommonUtil.throwsException(map, e);
		}
		return map; 
	}
	
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> delete(@RequestParam("json") String json){
		Map<String, String> map = new HashMap<String, String>();
		try {
			roleServices.deleteRoles(CommonUtil.getBean(json, Roles.class));
			map.put("mes", "删除成功");
		} catch (Throwable e) {
			CommonUtil.throwsException(map, e);
		}
		return map;//重定向
	}
	@RequestMapping("/setResource")
	public String setResource(HttpServletRequest request,@RequestParam("roleid")Integer roleid){
		request.setAttribute("roleid",roleid);
		return "/roleSetResources";
	}
	@RequestMapping("/loadResources")
	@ResponseBody
	public String loadResources(HttpServletRequest request,@RequestParam("roleid")Integer roleid){
		return treeBulid.buildAllTree(roleid,2,-2);
	}
	@RequestMapping(value="/saveResources",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> saveResources(HttpServletRequest request,@RequestParam("roleid")Integer roleid,@RequestParam("resid")Integer[] resid) throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		
		try {
			roleServices.saveRoleResource(roleid, resid);
			MySecurityMetadataSource.resourceMap = roleServices.loadResources();
			map.put("result", "succ");
		}
		catch (Throwable e) {
			e.printStackTrace();
			CommonUtil.throwsException(map, e);
		}
		return map; 
	}
	@SuppressWarnings("unused")
	private List<Map<String,Object>> buildTree(List<Resources> list,List<Resources> roleList){
		List<Map<String,Object>> rootElement = new ArrayList<Map<String,Object>>();
		Map<Integer,List<Map<String,Object>>> allElement = new LinkedHashMap<Integer,List<Map<String,Object>>>();
		for(Resources r : list){
			if(r.getParentid() == -1){
				Map<String,Object> obj = new HashMap<String,Object>();
				obj.put("id",r.getResouceid());
				obj.put("text",r.getName());
				obj.put("checked",roleList.contains(r));
				obj.put("state","opened");
				obj.put("iconCls","icon-computer");
				rootElement.add(obj);
			}else{
				List<Map<String,Object>> set = allElement.get(r.getParentid());
				if(set == null){
					set = new ArrayList<Map<String,Object>>();
				}
				Map<String,Object> obj = new HashMap<String,Object>();
				obj.put("id",r.getResouceid());
				obj.put("text",r.getName());
				obj.put("checked",roleList.contains(r));
				obj.put("state","closed");
				set.add(obj);
				allElement.put(r.getParentid(),set);
			}
		}
		Map<String,Object> map = new LinkedHashMap<String,Object>();
//		Collections.sort(rootElement, new Comparator<Map<String,Object>>(){
//			public int compare(Map<String,Object> o1, Map<String,Object> o2) {
//				return (Integer)o1.get("order") - (Integer)o2.get("order");
//			}
//		});
		for(Map<String,Object> pc : rootElement){
			pc.put("children", getSub((Integer)pc.get("id"),allElement));
		}
		return rootElement;
	}
	private List<Map<String,Object>> getSub(Integer id,Map<Integer,List<Map<String,Object>>> map){
		List<Map<String,Object>> list = map.get(id);
		if(list != null && list.size() > 0){
//			Collections.sort(list, new Comparator<Map<String,Object>>(){
//				public int compare(Map<String,Object> o1, Map<String,Object> o2) {
//					return (Integer)o1.get("order") - (Integer)o2.get("order");
//				}
//			});
			for(Map<String,Object> pc : list){
				pc.put("children", getSub((Integer)pc.get("id"),map));
			}
		}
		return list;
	}
}
